import { useContext } from '@/hooks'
import { nextTick, ref, Ref, watch, WatchStopHandle } from 'vue'
import { useRoute } from 'vue-router'

interface ReloadContext {
  reload: Ref<boolean>
  handleReload(): void
  /**
   * 添加重新加载动作的监听器
   * @param listener 重新加载动作回调函数
   */
  loadingListener(listener: () => void): WatchStopHandle
}

const { useProvide, useInject: useReloadInject } = useContext<ReloadContext>()

/** 重载上下文 */
export default function useReloadContext() {
  const reload = ref(true)
  function handleReload() {
    reload.value = false
    nextTick(() => {
      reload.value = true
    })
  }
  function loadingListener(listener: () => void) {
    const route = useRoute()
    const fullPath = route.fullPath
    return watch(reload, (newV, oldV) => {
      if (newV && !oldV && fullPath === route.fullPath) {
        listener()
      }
    })
  }

  const context: ReloadContext = {
    reload,
    handleReload,
    loadingListener,
  }

  function useReloadProvide() {
    useProvide(context)
  }

  return {
    context,
    useReloadProvide,
    useReloadInject,
  }
}
